package com.atguigu.bigdata.spark.zzgcore.rdd.operator.transform

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

/**
 * @Classname Spark01_RDD_Operation_Transfrom
 * @Description 相同的首字母放在一个组中
 * @Date 2023/9/20 15:23
 * @Author zhuzhenguo
 */
object Spark18_RDD_Operation_Transform3 {
  def main(args: Array[String]): Unit = {
    // 准备环境,这个 *表示系统当前最大可用核数
    val sparkConf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("Operator")
    val sc = new SparkContext(sparkConf)
    // k-v类型
    val rdd: RDD[(String, Int)] = sc.makeRDD(List(("a", 1), ("a", 2), ("b", 3)
      , ("b", 4), ("b", 5), ("a", 6)), 2)

    // aggregateByKey最终的放回数据结果应该和初始值的类型保持一致
    //    rdd.aggregateByKey(0)(_ + _, _ + _).collect().foreach(println)

    // 获取相同key的数据平均值 => (a,3),(b,4)
    val newRDD: RDD[(String, (Int, Int))] = rdd.aggregateByKey((0, 0))(
      (t, v) => {
        (t._1 + v, t._2 + 1)
      },
      (t1, t2) => {
        (t1._1 + t2._1, t1._2 + t2._2)
      }
    )

    val resultRDD: RDD[(String, Int)] = newRDD.mapValues {
      case (num, count) => {
        num / count
      }
    }

    resultRDD.collect().foreach(println)
    // 关闭环境
    sc.stop()
  }
}
